package com.blog.controller;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.blog.pojo.MLogin;
import com.blog.service.ILoginService;
import com.blog.util.CookieUtil;
import com.blog.util.JsonUtil;
import com.blog.util.RedisPoolUtil;

@Controller
@RequestMapping("/")
public class LoginController {

	
	@Autowired 
	private ILoginService loginService;
	
	
	@RequestMapping("/login")
	public String login(){
		return "blog/login";
		
	}
	
	
	//使用session存储
/*	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	public ModelAndView login(@RequestParam("name")String name,@RequestParam("password")String password,Model model,HttpSession session){
		
		
		MLogin user = loginService.selectUser(name,password);
		
		if(user == null){
			//不存在
			model.addAttribute("msg", "用户名或密码错误");
			return new ModelAndView("blog/login");
		}else{
			//存在
			session.setAttribute("user", user); 
			session.setAttribute("username", name);
			return new ModelAndView("redirect:/main");
		}
		
	}*/
	
	//改为使用redis
	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	public ModelAndView login(@RequestParam("name")String name,@RequestParam("password")String password,Model model,HttpSession session,HttpServletResponse response){
		
		 
		MLogin user = loginService.selectUser(name,password);
		
		if(user == null){
			//不存在
			model.addAttribute("msg", "用户名或密码错误");
			return new ModelAndView("blog/login");
		}else{
			//存在
			//session.setAttribute("user", user); 
			
			CookieUtil.writeLoginToken(response, session.getId());
			//过期时间为30分钟 （30s）
			RedisPoolUtil.setEx(session.getId(), JsonUtil.obj2String(user),30 * 60);
			
			session.setAttribute("username", name);
			return new ModelAndView("redirect:/main");
		}
		
	}
	
	@RequestMapping("/logout")
	public ModelAndView logout(HttpSession session){
		
		session.removeAttribute("loginUser");
		return new ModelAndView("redirect:/login");
		
	}
}
